<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 题目类型数据 -->
      <el-col :span="24">
        <el-card shadow="never">
          <!-- 查询条件 -->
          <div class="search-container">
            <div class="search-header">
              <el-button
                type="text"
                :icon="showSearch ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                @click="toggleSearch"
              >
                {{ showSearch ? '隐藏搜索' : '显示搜索' }}
              </el-button>
              <el-button
                type="text"
                icon="el-icon-setting"
                @click="showColumnDialog = true"
              >
                列设置
              </el-button>
            </div>

            <el-collapse-transition>
              <el-form
                v-show="showSearch"
                ref="queryForm"
                :model="queryParams"
                :inline="true"
                label-width="68px"
              >
                <el-form-item label="类型名称" prop="name">
                  <el-input
                    v-model="queryParams.name"
                    placeholder="请输入类型名称"
                    clearable
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="类型编码" prop="code">
                  <el-input
                    v-model="queryParams.code"
                    placeholder="请输入类型编码"
                    clearable
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-collapse-transition>
          </div>

          <!-- 操作按钮 -->
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                icon="el-icon-plus"
                @click="handleAdd"
                v-hasPermi="['question.js:type:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                icon="el-icon-delete"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['question.js:type:delete']"
              >删除</el-button>
            </el-col>
          </el-row>

          <!-- 表格数据 -->
          <el-table
            v-loading="loading"
            :data="typeList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              v-if="columns[0].visible"
              type="selection"
              width="55"
              align="center"
            />
            <el-table-column
              v-if="columns[1].visible"
              label="ID"
              prop="id"
              width="80"
              align="center"
            />
            <el-table-column
              v-if="columns[2].visible"
              label="类型名称"
              prop="name"
              align="center"
            />
            <el-table-column
              v-if="columns[3].visible"
              label="类型编码"
              prop="code"
              align="center"
            />
            <el-table-column
              v-if="columns[4].visible"
              label="选项配置"
              prop="hasOption"
              align="center"
            >
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.question_option_type"
                  :value="scope.row.hasOption === 0 ? '无选项' : scope.row.hasOption === 1 ? '单选' : '多选'"
                />
              </template>
            </el-table-column>
            <el-table-column
              v-if="columns[5].visible"
              label="需要答案"
              prop="hasAnswer"
              align="center"
            >
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.question_answer_type"
                  :value="scope.row.hasAnswer.toString()"
                />
              </template>
            </el-table-column>
            <el-table-column
              v-if="columns[6].visible"
              label="需要附件"
              prop="hasFile"
              align="center"
            >
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.sys_yes_no"
                  :value="scope.row.hasFile === 1 ? 'Y' : 'N'"
                />
              </template>
            </el-table-column>
            <el-table-column
              v-if="columns[7].visible"
              label="排序"
              prop="sort"
              align="center"
            />
            <el-table-column
              v-if="columns[8].visible"
              label="操作"
              align="center"
              width="180"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['question.js:type:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['question.js:type:delete']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改题目类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="类型编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入类型编码" />
        </el-form-item>
        <el-form-item label="选项配置" prop="hasOption">
          <el-radio-group v-model="form.hasOption">
            <el-radio
              v-for="dict in dict.type.question_option_type"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="需要答案" prop="hasAnswer">
          <el-radio-group v-model="form.hasAnswer">
            <el-radio
              v-for="dict in dict.type.question_answer_type"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
          <el-alert
            v-if="form.hasAnswer === '-1'"
            title="该类型题目答案可能涉及图表、复杂公式等数据，自动改卷暂不支持"
            type="warning"
            :closable="false"
            show-icon
            style="margin-top: 10px;"
          />
        </el-form-item>
        <el-form-item label="需要附件" prop="hasFile">
          <el-radio-group v-model="form.hasFile">
            <el-radio
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 列设置对话框 -->
    <el-dialog title="列设置" :visible.sync="showColumnDialog" width="500px" append-to-body>
      <el-form>
        <el-form-item>
          <el-checkbox-group v-model="columnOptions">
            <el-checkbox
              v-for="item in columns"
              :key="item.key"
              :label="item.key"
            >{{item.label}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveColumnSettings">确 定</el-button>
        <el-button @click="showColumnDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listType, getType, addType, updateType, delType } from "@/api/question2/type";

export default {
  name: "QuestionType",
  dicts: ['sys_yes_no','question_option_type', 'question_answer_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目类型表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示列设置对话框
      showColumnDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        code: undefined,
      },
      // 表单参数
      form: {},
      // 列设置
      columns: [
        { key: 'selection', label: '选择列', visible: true },
        { key: 'id', label: 'ID', visible: true },
        { key: 'name', label: '类型名称', visible: true },
        { key: 'code', label: '类型编码', visible: true },
        { key: 'hasOption', label: '选项配置', visible: true },
        { key: 'hasAnswer', label: '需要答案', visible: true },
        { key: 'hasFile', label: '是否有附件', visible: true },
        { key: 'sort', label: '排序', visible: true },
        { key: 'action', label: '操作', visible: true }
      ],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "类型名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "类型编码不能为空", trigger: "blur" }
        ],
        hasOption: [
          { required: true, message: "请选择选项配置", trigger: "change" }
        ],
        hasAnswer: [
          { required: true, message: "请选择是否需要答案", trigger: "change" }
        ],
        hasFile: [
          { required: true, message: "请选择是否需要上传附件", trigger: "change" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    columnOptions: {
      get() {
        return this.columns.filter(item => item.visible).map(item => item.key);
      },
      set(value) {
        this.columns.forEach(item => {
          item.visible = value.includes(item.key);
        });
      }
    }
  },
  created() {
    this.getList();
    this.loadColumnSettings();
  },
  methods: {
    /** 查询题目类型列表 */
    getList() {
      this.loading = true;
      listType(this.queryParams).then(response => {
        this.typeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
// 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        code: undefined,
        hasOption: '0',  // 默认值改为'Y'
        hasAnswer: '1',  // 默认主观答案
        hasFile: 'N',  // 默认值改为'Y'
        sort: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题目类型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getType(id).then(response => {
        this.form = {
          ...response.data,
          hasOption: response.data.hasOption === 0 ? '0' : response.data.hasOption === 1 ? '1' : '2',
          hasAnswer: String(response.data.hasAnswer), // 转换为字符串
          hasFile: response.data.hasFile === 1 ? 'Y' : 'N'
        };
        this.open = true;
        this.title = "修改题目类型";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 转换字典值为后端需要的格式
          const formData = {
            ...this.form,
            hasOption: this.form.hasOption === '0' ? 0 : this.form.hasOption === '1' ? 1 : 2,
            hasAnswer: parseInt(this.form.hasAnswer), // 直接转换为数字
            hasFile: this.form.hasFile === 'Y' ? 1 : 0
          };

          if (formData.id != null) {
            updateType(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addType(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除题目类型编号为"' + ids + '"的数据项？').then(function() {
        return delType(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 切换搜索区域显示 */
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },
    /** 加载列设置 */
    loadColumnSettings() {
      const savedSettings = localStorage.getItem('questionTypeColumns');
      if (savedSettings) {
        try {
          const settings = JSON.parse(savedSettings);
          this.columns.forEach(col => {
            if (settings[col.key] !== undefined) {
              col.visible = settings[col.key];
            }
          });
        } catch (e) {
          console.error('加载列设置失败:', e);
        }
      }
    },
    /** 保存列设置 */
    saveColumnSettings() {
      const settings = {};
      this.columns.forEach(col => {
        settings[col.key] = col.visible;
      });
      localStorage.setItem('questionTypeColumns', JSON.stringify(settings));
      this.showColumnDialog = false;
      this.$modal.msgSuccess("列设置保存成功");
    }
  }
};
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
}
.search-header {
  margin-bottom: 15px;
}
</style>
